var cluster = require('cluster');
var sticky = require('sticky-session');
var app = require('express')();
var server = require('http').Server(app);

if (!sticky.listen(server, 3000)) {
    // Master code
    console.log(`master[process:${process.pid}] node start...`);

    server.once('listening', function () {
        console.log('server started on 3000 port');
    });
} else {
    // Worker code
    console.log(`work[process:${process.pid}][work:${cluster.worker.id}] node start...`);

    app.get('/', function (req, res) {
        res.sendFile(__dirname + '/index.html');
    });

    app.get('/node', function (req, res) {
        res.end(`worker: ${cluster.worker.id} = ${global.workId}`);
    });

    var io = require('socket.io')(server);
    io.on('connection', function (socket) {

        console.log(`a user connected, worker: ${cluster.worker.id}`);

        socket.on('chat message', function (msg) {
            console.log(`message: ${msg}, worker: ${cluster.worker.id}`);
            socket.send(msg, (ack) => {
                console.log(`ack: ${JSON.stringify(ack)}`);
            });
        });

        socket.on('disconnect', function () {
            console.log(`user disconnected, worker: ${cluster.worker.id}`);
        });
    });

    global.io = io;
    global.workId = cluster.worker.id;
}